
package com.tg.app.socket;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.appbase.custom.base.UpdateStatus;
import com.appbase.custom.constant.CommonConstants;
import com.tange.module.socket.SocketIoConstants;
import com.tg.app.activity.device.NoDeviceActivity;
import com.tg.app.bean.FirmwareUpgrade;
import com.tg.app.bean.FirmwareUpgrade_;
import com.tg.app.util.ObjectBoxUtil;
import com.tange.base.toolkit.DateUtil;
import com.tg.appcommon.android.TGLog;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.appcommon.helper.LogoutDialogHelper;
import com.tg.push.PushConstants;

import org.json.JSONException;
import org.json.JSONObject;

import io.objectbox.Box;


/**
 * 后续废弃此类
 * 当前只用于分发消息了。
 *
 * 逻辑迁移到 SocketIoConnection
 */
@Deprecated
public class SocketIoService extends Service {

    public static final String TAG = "SocketIoService";

    private static final int MSG_SOCKET_CONNCETED = 0x01;
    private static final int MSG_SOCKET_DISCONNECT = 0x02;
    private static final int MSG_SOCKET_CONNECTERROR = 0x03;
    private static final int MSG_ADD_DEVICE = 0x04;
    private static final int MSG_UNBIND_DEVICE = 0x05;
    private static final int MSG_DEVICE_STATUS = 0x06;
    private static final int MSG_DEVICE_UPDATE_STATUS = 0x07;
    private static final int MSG_DEVICE_SHARE_STATUS = 0x08;
    private static final int MSG_ACCOUNT_LOGOUT = 0x09;

    private SocketEventBroadCastReceiver socketEventBroadCastReceiver;

    private class SocketEventBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            String event = intent.getStringExtra(SocketIoConstants.SOCKET_EVENT);
            String param = intent.getStringExtra(SocketIoConstants.SOCKET_PARAM);
            JSONObject data = null;
            try {
                data = new JSONObject(param);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            switch (event) {
                case SocketIoConstants.NOTIFY_ADD_DEVICE: {
                    Message msg = mServiceHandler.obtainMessage(MSG_ADD_DEVICE, data);
                    mServiceHandler.sendMessage(msg);
                }
                    break;
                case SocketIoConstants.NOTIFY_UNBIND_DEVICE: {

                    mServiceHandler.sendEmptyMessage(MSG_UNBIND_DEVICE);
                }
                    break;

                case SocketIoConstants.NOTIFY_DEVICE_STATUS: {
                    Message msg = mServiceHandler.obtainMessage(MSG_DEVICE_STATUS, data);
                    mServiceHandler.sendMessage(msg);
                }
                    break;

                case SocketIoConstants.NOTIFY_DEVICE_ACCOUNT_STATUS: {
                    String type = data.optString("type");
                    if (SocketIoConstants.NOTIFY_DEVICE_REMOTE_LOGIN.equalsIgnoreCase(type)) {
                        Message msg = mServiceHandler.obtainMessage(MSG_ACCOUNT_LOGOUT, data);
                        mServiceHandler.sendMessage(msg);
                    }
                }
                    break;

                case SocketIoConstants.NOTIFY_DEVICE_SHARE: {
                    Message msg = mServiceHandler.obtainMessage(MSG_DEVICE_SHARE_STATUS, data);
                    mServiceHandler.sendMessage(msg);
                }
                    break;

                case SocketIoConstants.NOTIFY_DEVICE_UPDATE_STATUS: {

                    TGLog.i(TAG, "onReceive: NOTIFY_DEVICE_UPDATE_STATUS");
                    UpdateStatus updateStatus = JSON.parseObject(data.toString(), UpdateStatus.class);
                    Box<FirmwareUpgrade> box = ObjectBoxUtil.getFirmwareUpgrade();
                    if (updateStatus != null && box != null && updateStatus.update_status == 10) {
                        FirmwareUpgrade firmwareUpgrade = box.query().equal(FirmwareUpgrade_.deviceId, updateStatus.device_id).build().findFirst();
                        if (firmwareUpgrade != null) {
                            firmwareUpgrade.progress = 100;
                            firmwareUpgrade.status = updateStatus.update_status;
                            firmwareUpgrade.updated_at = DateUtil.get2MillisYMDHHMMSS(updateStatus.update_finish_time);
                            box.put(firmwareUpgrade);
                        }

                    }
                }
                    break;

                case SocketIoConstants.DEVICE_DOORBELL: {
                    Intent pintent = new Intent();
                    pintent.setPackage(getApplicationContext().getPackageName());
                    pintent.setAction(PushConstants.ACIONT_RECEIVE);
                    pintent.putExtra(PushConstants.KEY_EXTRA,data.toString());
                    sendBroadcast(pintent);
                }
                break;
                default:
                    break;
            }
        }
    }

    private ServiceHandler mServiceHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        TGLog.i(TAG, "SocketIoService create");

        mServiceHandler = new ServiceHandler(Looper.getMainLooper());

        IntentFilter filter = new IntentFilter();
        filter.addAction(SocketIoConstants.SOCKET_EVENT_ACTION);
        socketEventBroadCastReceiver = new SocketEventBroadCastReceiver();
        registerReceiver(socketEventBroadCastReceiver, filter);
    }


    private void showLogoutDialog(final JSONObject object) {
        String time = DateUtil.getStrToTimeHm(object.optString("time"));
        TGThreadPool.executeOnUiThread(new Runnable() {
            @Override
            public void run() {
                LogoutDialogHelper.getInstance().showLogoutDialog(time);
            }
        });
    }

    private class ServiceHandler extends Handler {

        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            Intent intent = null;
            switch (msg.what) {
                case MSG_ACCOUNT_LOGOUT:
                    Intent offlineIntent = new Intent();
                    offlineIntent.setAction(CommonConstants.ACTION_INTENT_USER_OFFLINE);
                    sendBroadcast(offlineIntent);
                    showLogoutDialog((JSONObject) msg.obj);
                    break;
                case MSG_DEVICE_SHARE_STATUS:
                    intent = new Intent();
                    intent.setAction(NoDeviceActivity.ACTION_DEVICE_SHARE);
                    sendBroadcast(intent);
                    break;
                case MSG_SOCKET_CONNCETED:
                    intent = new Intent(SocketIoConstants.NOTIFY_SOCKET_CONNCETED);
                    sendBroadcast(intent);
                    break;
                case MSG_ADD_DEVICE:
                    TGLog.d(TAG, "handler add");
                    JSONObject data = (JSONObject) msg.obj;
                    intent = new Intent(SocketIoConstants.NOTIFY_ADD_DEVICE);
                    intent.putExtra(CommonConstants.EXT_DEVICE_ID, data.optLong("device_id"));
                    sendBroadcast(intent);
                    break;
                case MSG_UNBIND_DEVICE:
                    TGLog.d(TAG, "handler unbind");
                    intent = new Intent(SocketIoConstants.NOTIFY_UNBIND_DEVICE);
                    sendBroadcast(intent);
                    break;
                case MSG_DEVICE_STATUS:
                    TGLog.d(TAG, "handler device status");
                    JSONObject dataJson = (JSONObject) msg.obj;
                    intent = new Intent(SocketIoConstants.NOTIFY_DEVICE_STATUS);
                    intent.putExtra(SocketIoConstants.NOTIFY_KEY_DATA, dataJson.toString());
                    sendBroadcast(intent);
                    break;
            }
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (socketEventBroadCastReceiver != null) {
            unregisterReceiver(socketEventBroadCastReceiver);
        }
    }
}
